<template>
  <div class="courier-dashboard-container">
    <!-- 顶部欢迎区域 -->
    <el-card class="welcome-card" shadow="hover">
      <div class="welcome-content">
        <div class="welcome-text">
          <h2>欢迎回来，配送员</h2>
          <p>今天已送达 {{ stats.deliveredToday }} 单，完成配送 {{ stats.todayDeliveries }} 单，继续加油！</p>
        </div>
        <div class="action-buttons">
          <el-button type="primary" @click="$router.push('/availableOrders')">
            <el-icon><List /></el-icon>查看可接订单
          </el-button>
          <el-button @click="$router.push('/myAssignments')">
            <el-icon><Van /></el-icon>我的配送
          </el-button>
        </div>
      </div>
    </el-card>
    
    <!-- 配送状态卡片区域 -->
    <div class="stat-cards">
      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-info">
            <h3>今日配送</h3>
            <div class="stat-number">{{ stats.todayDeliveries }}</div>
            <div class="stat-desc">已完成配送订单</div>
          </div>
          <div class="stat-icon deliveries">
            <el-icon><Van /></el-icon>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-info">
            <h3>进行中</h3>
            <div class="stat-number">{{ stats.activeDeliveries }}</div>
            <div class="stat-desc">正在配送的订单</div>
          </div>
          <div class="stat-icon active">
            <el-icon><Document /></el-icon>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-info">
            <h3>可接订单</h3>
            <div class="stat-number">{{ stats.availableOrders }}</div>
            <div class="stat-desc">附近可接的订单</div>
          </div>
          <div class="stat-icon available">
            <el-icon><List /></el-icon>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-info">
            <h3>今日送达</h3>
            <div class="stat-number">{{ stats.deliveredToday }}</div>
            <div class="stat-desc">成功送达的订单</div>
          </div>
          <div class="stat-icon delivered">
            <el-icon><Location /></el-icon>
          </div>
        </div>
      </el-card>
    </div>
    
    <!-- 当前配送任务 -->
    <el-card class="active-orders-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <h3>当前配送任务</h3>
          <el-button type="primary" link @click="$router.push('/myAssignments')">查看全部</el-button>
        </div>
      </template>
      
      <div v-if="activeDeliveries.length > 0" class="active-deliveries">
        <div v-for="(delivery, index) in activeDeliveries" :key="delivery.assignmentId" class="delivery-item">
          <div class="delivery-status">
            <el-tag :type="getStatusType(delivery.status)" effect="dark">{{ getStatusText(delivery.status) }}</el-tag>
          </div>
          <div class="delivery-info">
            <div class="delivery-number">{{ delivery.orderNumber }}</div>
            <div class="delivery-address">
              <span class="address-label">收件地址：</span>
              {{ delivery.receiverAddress }}
            </div>
            <div class="delivery-time">
              <span class="time-label">分配时间：</span>
              {{ formatTime(delivery.assignedAt) }}
            </div>
            <div v-if="delivery.remark" class="delivery-remark">
              <span class="remark-label">备注：</span>
              {{ delivery.remark }}
            </div>
          </div>
          <div class="delivery-actions">
            <el-button type="primary" size="small" @click="handleUpdateStatus(delivery)">{{ getActionText(delivery.status) }}</el-button>
            <el-button size="small" @click="viewDeliveryDetail(delivery.orderId)">详情</el-button>
          </div>
        </div>
      </div>
      
      <div v-else class="empty-placeholder">
        <el-empty description="当前没有配送任务"></el-empty>
        <el-button type="primary" @click="$router.push('/availableOrders')">查看可接订单</el-button>
      </div>
    </el-card>
    

  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { 
  Document, 
  Van, 
  List,
  Location
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { getCourierDashboard, updateDeliveryStatus, type CourierDashboardData, type CurrentTask } from '@/api/courier'

const router = useRouter()
const loading = ref(true)

// 配送员统计数据
const stats = reactive({
  todayDeliveries: 0,        // 今日已完成配送
  activeDeliveries: 0,       // 正在进行的配送
  availableOrders: 0,        // 可接订单数量
  deliveredToday: 0          // 今日成功送达订单
})

// 当前配送任务
const activeDeliveries = ref<CurrentTask[]>([])

// 保存完整的仪表盘数据
const dashboardData = ref<CourierDashboardData | null>(null)

// 状态映射
const statusTextMap: Record<number, string> = {
  0: '待揽收',
  1: '待发货',
  2: '运输中',
  3: '待签收',
  4: '已完成'
}

// 订单状态映射
const orderStatusTextMap: Record<number, string> = {
  0: '待揽收',
  1: '待发货',
  2: '运输中',
  3: '待签收',
  4: '已完成'
}



// 获取状态类型
const getStatusType = (status: number) => {
  const typeMap: Record<number, string> = {
    0: 'primary', // 待揽收
    1: 'info',    // 待发货
    2: 'warning', // 运输中
    3: 'danger',  // 待签收
    4: 'success'  // 已完成
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: number) => {
  return statusTextMap[status] || '未知状态'
}

// 获取操作按钮文本
const getActionText = (status: number) => {
  const textMap: Record<number, string> = {
    0: '开始发货',
    1: '标记送达',
    2: '确认签收'
  }
  return textMap[status] || '更新状态'
}

// 格式化时间
const formatTime = (timeStr: string) => {
  const date = new Date(timeStr)
  const now = new Date()
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
  const targetDate = new Date(date.getFullYear(), date.getMonth(), date.getDate())
  
  if (targetDate.getTime() === today.getTime()) {
    return `今日 ${date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })}`
  } else {
    return date.toLocaleString('zh-CN', { 
      month: '2-digit', 
      day: '2-digit', 
      hour: '2-digit', 
      minute: '2-digit' 
    })
  }
}

// 查看配送详情
const viewDeliveryDetail = (orderId: number) => {
  router.push(`/myAssignments?orderId=${orderId}`)
}



// 更新配送状态
const handleUpdateStatus = async (delivery: CurrentTask) => {
  try {
    let nextStatus = delivery.status + 1
    if (nextStatus > 3) nextStatus = 3 // 最大状态为已签收
    
    await updateDeliveryStatus(delivery.assignmentId, nextStatus, `状态更新为：${statusTextMap[nextStatus]}`)
    ElMessage.success(`已更新订单 ${delivery.orderNumber} 的状态`)
    
    // 重新加载数据
    await loadDashboardData()
  } catch (error: any) {
    console.error('更新配送状态失败:', error)
    ElMessage.error(error.message || '更新配送状态失败')
  }
}

// 加载仪表盘数据
const loadDashboardData = async () => {
  try {
    loading.value = true
    const response = await getCourierDashboard()
    
    if (response.code === 200 && response.data) {
      const data = response.data
      
      // 保存完整数据
      dashboardData.value = data
      
      // 更新统计数据
      stats.todayDeliveries = data.todayCompleted
      stats.activeDeliveries = data.inProgress
      stats.availableOrders = data.availableOrders
      stats.deliveredToday = data.todayDelivered
      
      // 更新当前任务
      activeDeliveries.value = data.currentTasks || []
      
      console.log('仪表盘数据加载成功:', data)
    } else {
      throw new Error(response.message || '获取仪表盘数据失败')
    }
  } catch (error: any) {
    console.error('加载仪表盘数据失败:', error)
    ElMessage.error(error.message || '加载仪表盘数据失败')
  } finally {
    loading.value = false
  }
}



onMounted(async () => {
  // 加载仪表盘数据
  await loadDashboardData()
})
</script>

<style scoped>
.courier-dashboard-container {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 欢迎卡片 */
.welcome-card {
  background: linear-gradient(135deg, #67C23A 0%, #529b2e 100%);
  color: white;
  border: none;
}

.welcome-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.welcome-text h2 {
  margin: 0 0 10px 0;
  font-size: 24px;
}

.welcome-text p {
  margin: 0;
  opacity: 0.8;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

/* 统计卡片 */
.stat-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.stat-card {
  border-radius: 12px;
  transition: all 0.3s ease;
  border: 1px solid #f0f0f0;
}

.stat-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.12);
  border-color: transparent;
}

.stat-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stat-info h3 {
  font-size: 14px;
  color: #909399;
  margin: 0 0 10px 0;
}

.stat-number {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 8px;
  color: #303133;
}

.stat-desc {
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
}

.stat-icon.deliveries {
  background: linear-gradient(135deg, #67C23A, #85ce61);
}

.stat-icon.active {
  background: linear-gradient(135deg, #E6A23C, #ebb563);
}

.stat-icon.available {
  background: linear-gradient(135deg, #409EFF, #66b1ff);
}

.stat-icon.delivered {
  background: linear-gradient(135deg, #F56C6C, #f78989);
}

.active-orders-card {
  min-height: 300px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  font-size: 16px;
  font-weight: 600;
  margin: 0;
}

.empty-placeholder {
  margin: 40px 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

/* 当前配送任务 */
.active-deliveries {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.delivery-item {
  display: flex;
  flex-wrap: wrap;
  padding: 16px;
  border-radius: 8px;
  background-color: #f5f7fa;
  align-items: center;
}

.delivery-status {
  margin-right: 16px;
}

.delivery-info {
  flex: 1;
  min-width: 200px;
}

.delivery-number {
  font-weight: 600;
  margin-bottom: 8px;
}

.delivery-address, .delivery-time, .delivery-remark {
  color: #606266;
  font-size: 14px;
  margin-bottom: 4px;
}

.address-label, .time-label, .remark-label {
  color: #909399;
}

.delivery-actions {
  display: flex;
  gap: 8px;
  margin-left: 16px;
}



@media (max-width: 768px) {
  .stat-cards {
    grid-template-columns: 1fr;
  }
  
  .welcome-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .delivery-item {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .delivery-status, .delivery-info, .delivery-actions {
    margin: 8px 0;
    width: 100%;
  }
}
</style>